<template>
  <div id="gift-category">
    <Row type="flex"
         align="middle"
         justify="end"
         style="padding:20px">
      <Col><Button type="primary"
              @click="add"
              style="width:80px;">添加</Button></Col>
    </Row>
    <div class="table">
      <Table :columns="columnsData"
             :height="this.tableHeight"
             class="table-list"
             :data="dataList"
             stripe
             :loading='loading'>
        <template slot-scope="{ row }"
                  slot="name">
          <span>{{row.categoryName}}</span>
        </template>
        <template slot-scope="{ row }"
                  slot="super">
          <span>{{row.parent?row.parent.categoryName:null}}</span>
        </template>
        <template slot-scope="{ row, index }"
                  slot="action">
          <!-- <Icon type="md-create"
                custom="i-icon i-icon-shop_fill"
                style="padding-right:13px;"
                size="17"
                @click="edit(row, index)" /> -->
          <i class="iconsys iconedit"
             @click="edit(row,index)"
             title="编辑">
          </i>
          <Poptip confirm
                  title="你确定要删除吗？"
                  @on-ok="del(row, index)"
                  @on-cancel="cancel(row, index)"
                  style="text-align:left;">
            <i class="iconsys icondel"
               title="删除">
            </i>
            <!-- <Icon type="md-trash"
                  custom="i-icon i-icon-shop_fill"
                  style="padding-right:13px;"
                  size="17" /> -->
          </Poptip>
        </template>
      </Table>
      <Row type='flex'
           justify="end"
           class="page-bottom">
        <Col>
        <Page :total="total"
              :page-size='pageSize'
              show-sizer
              show-total
              @on-change='changePage'
              @on-page-size-change='changePageSize' />
        </Col>
      </Row>
      <Drawer :title="title"
              :closable="true"
              v-model="drawShow"
              width='540'
              :transfer='false'>
        <Row type='flex'
             justify="center"
             style="padding-top:20px">
          <Col>
          <Form ref="formDynamic"
                :model="formDynamic"
                :rules="ruleValidate"
                :label-width="90">
            <FormItem label="上级类别："
                      prop='super'
                      id="super">
              <Select v-model="formDynamic.super"
                      clearable
                      style="width:280px"
                      :disabled='disabled'
                      :label-in-value='true'>
                <Option v-for="item in selectList"
                        :value="item.categoryName"
                        :key="item.categoryId"
                        :label="item.categoryName"
                        @click.native="selectOption(item)">{{ item.categoryName }}</Option>
              </Select>
            </FormItem>
            <FormItem label="类别名称："
                      prop='name'>
              <Input v-model="formDynamic.name"
                     style="width:280px"
                     clearable
                     :maxlength="10"
                     @on-keyup='keyUp'
                     placeholder="最多可输入10字"></Input>
            </FormItem>
          </Form>
          </Col>
        </Row>
        <Row type='flex'
             justify="end"
             class="bottom-form-item">
          <Col>
          <Button style="width:80px"
                  @click='handleCancel'>取消</Button>
          <Button type='primary'
                  :disabled='isDisabled'
                  @click="handleSubmit('formDynamic')"
                  style="margin-left:20px;width:80px">确定</Button>
          </Col>
        </Row>
      </Drawer>
    </div>
  </div>
</template>

<script>
import { getProductCategory, getProductAdd, getProductDel } from '@/api/setting'
export default {
  data () {
    return {
      tableHeight: 0,
      loading: true,
      total: 0,
      pageSize: 10,
      pageIndex: 1,
      disabled: false,
      isDelete: true,
      drawShow: false,
      isDisabled: false,
      title: '添加礼品类别',
      paramter: {
        'shopId': this.$route.query.id,
        'merchantId': this.$store.state.user.merchantId
      },
      columnsData: [
        {
          title: ' ',
          width: 70
        },
        {
          title: '类别名称',
          slot: 'name'
        },
        {
          title: '上级类别',
          slot: 'super'
        },
        {
          title: '操作',
          slot: 'action',
          width: '300'
        }
      ],
      dataList: [],
      formDynamic: {
        name: '',
        super: ''
      },
      categoryId: '',
      ruleValidate: {
        name: { required: true, message: '礼品类别名称不能为空', trigger: 'blur' }
      },
      selectList: [],
      superId: ''
    }
  },
  watch: {
    drawShow (val) {
      if (val) {
        let subParam = { 'categoryType': 1, 'parentId': '0' }
        getProductCategory({ ...this.paramter, ...subParam }).then(res => {
          if (res.data.status === 200) {
            this.selectList = res.data.data
          } else {
            this.$Message.error({
              content: `${res.data.error}`,
              duration: 3
            })
          }
        })
      } else {
        this.$refs.formDynamic.resetFields()
        this.formDynamic = {
          name: '',
          super: ''
        }
        this.superId = ''
        this.disabled = false
      }
    }
  },
  methods: {
    changePage (page) {
      this.pageIndex = page
      this.getData()
    },
    changePageSize (size) {
      this.pageSize = size
      this.getData()
    },
    keyUp (e) {
      e.target.value = e.target.value.replace(/\s+/g, '')
    },
    selectOption (item) {
      this.superId = item.categoryId
    },
    add () {
      this.drawShow = true
      this.title = '添加礼品类别'
    },
    edit (row, index) {
      this.drawShow = true
      this.title = '编辑礼品类别'
      this.categoryId = row.categoryId
      this.formDynamic.name = row.categoryName
      this.superId = row.parentId
      if (row.parent) {
        this.formDynamic.super = row.parent.categoryName
      }
      if (row.parentId === '0') {
        this.disabled = true
      }
    },
    del (row, index) {
      if (this.isDelete) {
        if (!this.isDelete) {
          return
        }
        this.isDelete = false
        setTimeout(() => {
          getProductDel({ 'categoryId': row.categoryId }).then(res => {
            if (res.data.status === 200) {
              this.$Message.success(`删除成功`)
              this.isDelete = true
              this.getData()
            } else {
              this.isDelete = true
              this.$Message.error({
                content: `${res.data.error}`,
                duration: 3
              })
            }
          })
        }, 200)
      }
    },
    cancel (row, index) {
    },
    handleCancel () {
      this.drawShow = false
      this.$refs.formDynamic.resetFields()
    },
    handleSubmit (name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          // 防止误操作
          if (this.isDisabled) {
            return
          }
          this.isDisabled = true
          let other = { 'categoryType': 1, 'categoryName': this.formDynamic.name, 'parentId': '0' }
          if (this.title === '添加礼品类别') {
            setTimeout(() => {
              getProductAdd({ ...this.paramter, ...other, 'parentId': this.superId ? this.superId : '0' }).then(res => {
                this.isDisabled = false
                if (res.data.status === 200) {
                  this.drawShow = false
                  this.$Message.success('添加成功')
                  this.getData()
                } else {
                  this.drawShow = false
                  this.$Message.error({
                    content: `${res.data.error}`,
                    duration: 3
                  })
                }
              })
            }, 200)
          } else if (this.title === '编辑礼品类别') {
            setTimeout(() => {
              getProductAdd({ ...this.paramter, ...other, 'categoryId': this.categoryId, 'parentId': this.superId ? this.superId : '0' }).then(res => {
                this.isDisabled = false
                if (res.data.status === 200) {
                  this.drawShow = false
                  this.$Message.success('编辑成功')
                  this.getData()
                } else {
                  this.drawShow = false
                  this.$Message.error({
                    content: `${res.data.error}`,
                    duration: 3
                  })
                }
              })
            }, 200)
          }
        }
      })
    },
    getData () {
      this.loading = true
      this.tableHeight = 0
      let key = { 'categoryType': 1, 'limit': String(this.pageSize), 'offset': String(this.pageSize * (this.pageIndex - 1)) }
      getProductCategory({ ...this.paramter, ...key }).then(res => {
        if (res.data.status === 200) {
          this.loading = false
          this.dataList = res.data.data
          this.total = Number(res.data.totalCount)
          if (res.data.data && res.data.data.length >= 10) {
            this.tableHeight = 520
          }
          if (res.data.data.length / this.pageSize === 0) {
            if (this.pageIndex > 1) {
              this.pageIndex--
              this.getData()
            }
          }
        } else {
          this.loading = false
          this.$Message.error({
            content: `${res.data.error}`,
            duration: 3
          })
        }
      })
    }
  },
  mounted () {
    this.getData()
    if (!this.hasPermission('moms:setting:giftcategory')) {
      this.$router.replace({ name: 'error_401' })
    }
  }
}
</script>

<style lang='less'>
#gift-category {
  .page-bottom {
    padding: 15px;
  }
  .bottom-form-item {
    width: 100%;
    padding: 20px 30px;
    border-top: 1px solid #e8eaec;
    position: absolute;
    right: 0;
    bottom: 0;
  }
}
</style>
